package com.example.expandablelistview.network;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.expandablelistview.R;

public class DownloadManagerEx extends Activity {
	DownloadManager mDm;
	long mId = 0;
	ImageView image;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.downloadmanager);

		mDm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
		image = (ImageView) findViewById(R.id.image);
	}

	public void onPause() {
		super.onPause();
		if (mId != 0) {
			unregisterReceiver(mDownComplete);
		}
	}

	BroadcastReceiver mDownComplete = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			Toast.makeText(context, "다운로드 완료", Toast.LENGTH_LONG).show();
		}
	};

	public void mOnClick(View v) {

		switch (v.getId()) {

			case R.id.btnqueue:
				Uri uri = Uri
						.parse("http://developer.android.com/images/home/kk-hero.jpg");
				DownloadManager.Request req = new DownloadManager.Request(uri);
				req.setTitle("테스트 다운로드");
				req.setDescription("이미지 파일을 다운로드 받습니다.");
				req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
						| DownloadManager.Request.NETWORK_MOBILE);

				mId = mDm.enqueue(req);

				IntentFilter filter = new IntentFilter();
				filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

				registerReceiver(mDownComplete, filter);
				break;
			case R.id.btnview:
				try {
					ParcelFileDescriptor file;
					file = mDm.openDownloadedFile(mId);
					FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(
							file);
					Bitmap bm = BitmapFactory.decodeStream(fis);
					image.setImageBitmap(bm);
				} catch (FileNotFoundException e) {
					Toast.makeText(this, "파일이 없음", Toast.LENGTH_LONG).show();
				}
				break;

			case R.id.btndelete:
				if (mDm.remove(mId) == 1) {
					Toast.makeText(this, "삭제 완료", Toast.LENGTH_LONG).show();
					image.setImageBitmap(null);
				}
				break;
		}// end of switch
	}// end of mOnClick
}// end of class
